package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //调用mapper递归查询出分类信息
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //封装为List<CourseCategoryTreeDto>类型  找到每个节点的子节点
        //先将list转为map  key  节点id  value  TreeDto对象 方便从map获取节点
        Map<String, CourseCategoryTreeDto> mapTemp =
                courseCategoryTreeDtos.stream()
                        .filter(item -> !id.equals(item.getId()))
                        .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //定义一个list作为最终返回的list
        List<CourseCategoryTreeDto> courseCategoryTreeList=new ArrayList<>();

        //从头遍历List<CourseCategoryTreeDto>  一遍一遍找子节点放在父节点的ChildrenTreeNode
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            //向list中写入元素
            if(item.getParentid().equals(id)){
                courseCategoryTreeList.add(item);
            }
            //找到节点的父节点

            CourseCategoryTreeDto courseCategoryParent = mapTemp.get(item.getParentid());
            if (courseCategoryParent != null) {
                if (courseCategoryParent.getChildrenTreeNodes()==null){
                    //父节点属性为空 需要new一个空集合  因为需要向该集合放入子节点
                    courseCategoryParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                //放入子节点到父节点的childrenTreeNodes
                courseCategoryParent.getChildrenTreeNodes().add(item);
            }


        });


        return courseCategoryTreeList;
    }
}
